<template>
  <div >
    <!-- <category-panel title="分类" icon="tree" request="welfareCategory" @delClick="delClick" @notClick="notClick"
                    @nodeClick="nodeClick"></category-panel> -->
    <el-container>
      <el-header
        style="display:flex;align-items: center;justify-content: space-between;padding: 10px;border-bottom: 1px solid #f2f2f2;">
        <div>
          <svg-icon class="primary" :icon-class="$route.meta.icon"/>
          <span class="primary">{{companyName}}充值记录</span>
        </div>
        <div class="header-button-container">
          <el-button :icon="queryType? 'el-icon-search':'el-icon-close'" type="primary"
                     @click="chooseClick">{{queryType == false?'隐藏':'查询'}}
          </el-button>
          <ExportList2Excel ref="exportList2Excel"  @handleExport="handleExport"/>
        </div>
      </el-header>
      <div class="pd10">
          <div style="margin-bottom: 10px;display: flex;align-items: center" v-show="queryType == false">
            <el-date-picker v-model="query.createYear" type="year" placeholder="选择年份">
            </el-date-picker>
            <el-input prefix-icon="el-icon-search" placeholder="福利卡名称" style="width: 200px;margin-left: 10px"
                      v-model="query.memo"></el-input>
            <el-button style="margin-left: 10px" icon="el-icon-search" type="primary" @click="queryClick">
              查询
            </el-button>
            <el-button style="margin-left: 10px" icon="el-icon-refresh-right" type="info"
                       @click="resetClick">
              重置
            </el-button>
          </div>
        <el-table
          :data="memberData"
          border
          stripe
          v-loadMore="[payLoads,'rechargeList']"
          :height="curHeight"
          ref="table"
          style="width: 100%;">
          <el-table-column
            label="福利卡批次号"
            align="center"
            prop="batchNum"
          >
          </el-table-column>
          <el-table-column
            label="福利卡名称"
            align="center"
            prop="memo"
          >
          </el-table-column>
          <el-table-column
            label="充值人数"
            align="center"
            prop="num"
            width="100"
          >
          </el-table-column>
          <!-- <el-table-column
            label="每人福利金额"
            align="center"
            prop="amount"
            width="100"
          >
          </el-table-column> -->
          <el-table-column
            label="福利总金额"
            align="center"
            prop="totalBalance"
            width="100"
          >
          </el-table-column>
          <!-- <el-table-column
            label="福利总余额"
            align="center"
            prop="balance"
            width="100"
          >
          </el-table-column> -->
          <el-table-column
            label="充值到账时间"
            prop="createDate"
            align="center"
          >
            <template slot-scope="scope">
            <span>
              {{ scope.row.createDate | formatDateAndTime}}
            </span>
            </template>
          </el-table-column>
          <el-table-column
            label="有效期开始时间"
            prop="startDate"
            align="center"
          >
            <template slot-scope="scope">
            <span>
              {{ scope.row.startDate | formatDate}}
            </span>
            </template>
          </el-table-column>
          <el-table-column
            label="有效期结束时间"
            prop="endDate"
            align="center"
          >
            <template slot-scope="scope">
            <span>
              {{ scope.row.endDate | formatDate}}
            </span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="left" fixed="right" width="100">
            <template slot-scope="scope">
              <div>
                <el-tooltip class="item" effect="dark" content="修改福利卡信息" v-show="deleted == true" placement="top-start">
                  <a @click="editClick(scope.row)">
                    <i style="color: #409EFF" class="el-icon-edit"></i>
                  </a>
                </el-tooltip>
                <el-tooltip class="item" effect="dark" content="导出充值明细" v-show="deleted == false" placement="top-start">
                  <a style="margin-left: 10px" @click="detailClick(scope.row)">
                    <i style="color: #409EFF" class="el-icon-document"></i>
                  </a>
                </el-tooltip>
                <!-- <el-tooltip class="item" v-permission="['company.del']" effect="dark" content="恢复福利卡" v-show="deleted == true" placement="top-start">
                  <a style="margin-left: 10px" @click="restoreMchCourse(scope.row)">
                    <i style="color: #E6A23C" class="el-icon-refresh-right"></i>
                  </a>
                </el-tooltip> -->
                <el-tooltip class="item" effect="dark" content="删除福利卡" v-show="deleted == false" placement="top-start">
                  <a style="margin-left: 10px" @click="deleteMember(scope.row)">
                    <i style="color: #F56C6C" class="el-icon-delete"></i>
                  </a>
                </el-tooltip>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-footer class="el-footerBox">
        <pagination v-show="total>0" :total="total" :page.sync="pageNum" :limit.sync="pageSize"
                    @pagination="loadMember"></pagination>
      </el-footer>
    </el-container>
  </div>
</template>

<style scoped>
</style>

<script>
  import permission from '@/directive/permission/index.js' // 权限判断指令
  import utils from '../../utils/utils.js'
  import {selectCompanyAllCard, selectCompanyCardDetail,delCompanyCard} from '@/api/cardBill'
  import {EventBus} from '@/api/eventBus'
  import Pagination from '@/components/Pagination';
  import CategoryPanel from '@/components/CategoryPanel'
  import ExportList2Excel from '@/components/ExportList2Excel'
  import loadMore from '@/utils/loadMore.js'
  export default {
    name: 'company-list',
    directives: { permission },
    data() {
      return {
        memberData: [],
        pageNum: 1,
        pageSize: 20,
        total: 0,
        queryType: true,
        query: {
            memo : "",
            createYear : ""
        },
        keyword: {
            memo : "",
            createYear : ""
        },
        queryPhone: '',
        queryName: '',
        curHeight: null,
        excelData: [],
        companyCategoryId: '',
        deleted: false,
        restoreForm: {
          id: '',
          deleted: false,
        },
        payLoads:"",
        companyId:"",
        companyName:""
      }
    },
    components: {Pagination, CategoryPanel, ExportList2Excel},
    created() {
      var _this = this
      _this.companyId = this.$route.query.companyId;
      _this.companyName = this.$route.query.companyName;
      console.log("我是在外面的_this.companyId--"+JSON.stringify(_this.companyId) )
      this.loadMember()
      EventBus.$on('recharge', res => { // 监听新增完毕
        // 更新列表数组
        console.log("福利卡创建成功res--"+JSON.stringify(res) )
        _this.companyId = res.id;
        _this.companyName = res.name;
        this.loadMember()
      });
      EventBus.$on('company-edit', res => { // 监听新增完毕
        // 更新列表数组
        for (var i = 0; i < _this.memberData.length; i++) {
          if (_this.memberData[i].id == res.id) {
            _this.memberData[i] = res
          }
        }
      })
    },

    activated() {
        var _this = this
      _this.companyId = this.$route.query.companyId;
      _this.companyName = this.$route.query.companyName;
      console.log("我是在外面的_this.companyId--"+JSON.stringify(_this.companyId) )
      this.loadMember()
        this.payLoads = new Date().getTime();
    },
    mounted() {
      this.comeIn()
      this.beforeMount()
    },

    filters: {
      formatDateAndTime: function (value) {
        let date = new Date(value);
        let y = date.getFullYear();
        let MM = date.getMonth() + 1;
        MM = MM < 10 ? ('0' + MM) : MM;
        let d = date.getDate();
        d = d < 10 ? ('0' + d) : d;
        let h = date.getHours();
        let m = date.getMinutes();
        let s = date.getSeconds();
        return y + '-' + MM + '-' + d + " " + h + ":" + m + ":" + s;
      },

      formatDate: function (value) {
        let date = new Date(value);
        let y = date.getFullYear();
        let MM = date.getMonth() + 1;
        MM = MM < 10 ? ('0' + MM) : MM;
        let d = date.getDate();
        d = d < 10 ? ('0' + d) : d;
        return y + '-' + MM + '-' + d ;
      },

    },

    methods: {
        //时间的过滤器
        formatDateAndTime(value) {
            let date = new Date(value);
            let y = date.getFullYear();
            let MM = date.getMonth() + 1;
            MM = MM < 10 ? ('0' + MM) : MM;
            let d = date.getDate();
            d = d < 10 ? ('0' + d) : d;
            let h = date.getHours();
            h = h < 10 ? ('0' + h) : h;
            let m = date.getMinutes();
            m = m < 10 ? ('0' + m) : m;
            let s = date.getSeconds();
            s = s < 10 ? ('0' + s) : s;
            return y + '-' + MM + '-' + d + " " + h + ":" + m + ":" + s;
        },

        formatDate(value) {
            let date = new Date(value);
            let y = date.getFullYear();
            let MM = date.getMonth() + 1;
            MM = MM < 10 ? ('0' + MM) : MM;
            let d = date.getDate();
            d = d < 10 ? ('0' + d) : d;
            return y + '-' + MM + '-' + d ;
        },

        formatList(data){
            console.log("formatList--data--"+JSON.stringify(data) )
            if(data.length > 0){
                data.map((item)=>{
                    item.createDate = this.formatDateAndTime(item.createDate)
                    item.startDate = this.formatDate(item.startDate)
                    item.endDate = this.formatDate(item.endDate)
                })
            }
            return data
        },

        //充值卡的表格数据导出的函数
      handleExport(PageParam){
          var _this = this;

          //要导出函数携带的参数
        let data ={}
        data.tHeader = ["福利卡批次号","福利卡名称","充值员工人数","福利总余额","充值时间","有效期开始时间","有效期结束时间"]
        data.filterVal = ["batchNum","memo","num","totalBalance","createDate","startDate","endDate"]
        data.filename = _this.companyName+"企业福利充值列表"

        let pageInfo = {
            pageNum :  _this.pageNum,
            pageSize :  10000,
        }
        let sendData = {
            companyId : _this.companyId,
            memo : _this.keyword.memo,
            createYear : _this.keyword.createYear
        }
        selectCompanyAllCard(pageInfo, sendData).then(response => {
          console.log("请求的企业福利卡信息--"+JSON.stringify(response) )
          data.list = this.formatList(response.data.data);
            _this.$refs.exportList2Excel.handleDownload(data);
        }).catch(error => {
          console.log('error!!')
        });
      },

        //福利卡的充值明细导出
      detailClick(row){
          console.log("点击的行信息row"+JSON.stringify(row) )
        var _this = this;

          //要导出函数携带的参数
        let data ={}
        data.tHeader = ["福利卡批次号","福利卡名称","员工姓名","充值福利金额","福利金到账时间","有效期开始时间","有效期结束时间"]
        data.filterVal = ["batchNum","memo","name","balance","createDate","startDate","endDate"]
        data.filename = row.batchNum + "号批次的" + row.memo + "充值明细表"
        console.log("导出的数据data"+JSON.stringify(data) )

        let pageInfo = {
            pageNum :  1,
            pageSize :  10000,
        }
        let sendData = {
            companyId : _this.companyId,
            batchNum : row.batchNum
        }
        console.log("请求的企业信息sendData"+JSON.stringify(sendData) )
        selectCompanyCardDetail(pageInfo, sendData).then(response => {
          console.log("请求的企业信息"+JSON.stringify(response))
            data.list = this.formatList(response.data.data);
            console.log("请求的企业信息data"+JSON.stringify(data))
            _this.$refs.exportList2Excel.handleDownload(data);
        }).catch(error => {
          console.log('error!!')
        });
      },

      beforeMount() {
        window.onresize = () => {
          return (() => {
            if (this.queryType == false) {
              var h = document.documentElement.clientHeight || document.body.clientHeight;
              this.curHeight = h - 266//减去页面上固定高度height
            } else {
              var h = document.documentElement.clientHeight || document.body.clientHeight;
              this.curHeight = h - 220//减去页面上固定高度height
            }
          })();
        };
      },

      comeIn(){
        console.log('222')
        var h = document.documentElement.clientHeight || document.body.clientHeight;
        this.curHeight = h - 220//减去页面上固定高度height
      },

      editClick(row) {
        this.$router.push({
          path: '/company/edit', query: {id: row.id}
        })
      },

      //卡列表请求事件
      loadMember(val) {
        console.log("我被执行了，我是福利卡信息")
        var _this = this
        let pageInfo = {
            pageNum :  _this.pageNum,
            pageSize :  _this.pageSize,
        }
        let sendData = {
            companyId : _this.companyId,
            memo : _this.keyword.memo,
            createYear : _this.keyword.createYear
        }
        console.log("请求的企业福利卡信息--"+JSON.stringify(sendData) )
        selectCompanyAllCard(pageInfo, sendData).then(response => {
          console.log("请求的企业福利卡信息--"+JSON.stringify(response) )
          _this.memberData = response.data.data
          _this.total = response.data.total
          _this.updateScroll()
        }).catch(error => {
          console.log('error!!')
        });
      },

      chooseClick() {
        this.queryType = !this.queryType
        if (this.queryType == false) {
          var h = document.documentElement.clientHeight || document.body.clientHeight;
          this.curHeight = h - 266//减去页面上固定高度height
        } else {
          var h = document.documentElement.clientHeight || document.body.clientHeight;
          this.curHeight = h - 220//减去页面上固定高度height
        }
      },

      //按批次删除卡
      deleteMember(data) {
        console.log("data"+JSON.stringify(data))
        var _this = this
        this.$confirm('确认删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
            console.log("data.batchNum"+JSON.stringify(data.batchNum))
          delCompanyCard(data.batchNum).then(response => {
            console.log("删除成功后返回的数据--"+JSON.stringify(response))
            _this.memberData.forEach(function (item,index) {
              if (item.batchNum == data.batchNum){
                  console.log("删除成功后返回的数据item--"+JSON.stringify(item))
                _this.memberData.splice(index,1)
              }
            });
            _this.$message({
              message: response.content,
              offset: 120,
              center: true
            });
          }).catch(error => {
            console.log('error!!')
          });
        }).catch(() => {
        });
      },

      //查询的点击事件
      queryClick() {
        console.info("this.query--"+JSON.stringify(this.query.createYear))
        this.keyword.createYear = new Date(this.query.createYear).getFullYear();
        this.keyword.memo = this.query.memo;
        this.pageNum = 1
        this.loadMember()
      },

      resetClick() {
        this.query.createYear = '';
        this.query.memo = '';
        this.keyword = this.query;
        this.pageNum = 1;
        this.loadMember()
      },

      notClick() {
        this.companyCategoryId = 0;
        this.deleted = false;
        // this.loadMember()
      },
      delClick() {
        this.deleted = true;
        this.companyCategoryId = '';
        // this.loadMember()
      },
      nodeClick(data) {
        this.deleted = false;
        this.companyCategoryId = data.id
        // this.loadMember()
      },
      restoreMchCourse(row) {
        var _this = this
        console.log(row);
        this.$confirm('确认恢复?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.restoreForm.id = row.id;
          update(_this.restoreForm).then(response => {
            console.log(response);
            _this.memberData.forEach(function(item, index) {
              if (item.id == row.id) {
                _this.memberData.splice(index, 1)
              }
            })
            _this.$message({
              message: response.content,
              offset: 120,
              center: true
            });
          }).catch(error => {
            console.log('error!!')
          });
        }).catch(() => {
        });
      },

      //重置缓存的滚动距离
    updateScroll() {
        window.sessionStorage.setItem("loadTopcompany-list-table", 0);
        window.sessionStorage.setItem("loadLeftcompany-list-table", 0);
    }
    }
  }
</script>

<style scoped>
  .el-footerBox {
    height: 50px !important;
    line-height: 50px !important;
    border-top: 1px solid #f2f2f2;
  }
</style>
